package com.sy.server.service.impl;

import com.sy.server.util.MyConst;
import com.sy.server.dao.RedisDAO;
import com.sy.server.util.IpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Iterator;
import java.util.Set;

@Service
public class IpService {
    @Autowired
    private RedisDAO rdao;
    @Autowired
    private HttpServletRequest request;
    private final Logger logger= LoggerFactory.getLogger(IpService.class);

    public Integer getUserIdByCurrentIp() {
        String curIp= IpUtil.getIpAddress(request);
        Set set=rdao.keys(curIp+"*"+ MyConst.LOCK_SUFFIX);
        if(!set.isEmpty()){
            int userId=Integer.parseInt(rdao.getString((String)set.iterator().next()).toString());
            return userId;
        }
        return 0;
    }

    public String getUserNameByCurrentIp() {
        String curIp=IpUtil.getIpAddress(request);
        logger.info("[IpService] getUserNameByCurrentIp, curIp={}, city={}",curIp,IpUtil.getCityInfo(curIp));
        Set curIpSet=rdao.keys(curIp+"*"+MyConst.LOCK_SUFFIX);
        Iterator iterator=curIpSet.iterator();
        String userName="";
        if(iterator.hasNext()){
            String k=(String)iterator.next();//ip:songyang-lock
            userName=k.substring(k.indexOf(":")+1,k.indexOf("-"));
        }
        return userName;
    }
}
